#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/2 9:09
# @Author  : 1823218990@qq.com
# @File    : split_vc.py
# @Software: Pycharm

from datetime import datetime
import time
import shutil
import sys
import os
real_cfile = os.path.abspath(__file__)
real_path = os.path.dirname(real_cfile)
sys.path.append(real_path)
if not sys.platform.startswith("win"):
    raise Exception("can not run on this system: {}".format(sys.platform))
try:
    from vccut import VideaCut
except Exception as e:
    print(e)
    raise Exception(e)


class SplitVc(object):
    def __init__(self, inputfile, outputfile, split_list):
        self.inputfile = inputfile
        self.outputfile = outputfile
        self.split_list = split_list
        self.temp_dir = "\\tmp\\vccut"
        self.check_args()

    def check_args(self):
        if not os.path.exists(self.inputfile):
            raise Exception("{} not fount".format(self.inputfile))
        if not os.path.exists(self.temp_dir):
            os.makedirs(self.temp_dir)

        if os.path.isdir(self.outputfile):
            raise Exception("{} is dir".format(self.outputfile))
        else:
            if not os.path.exists(os.path.dirname(self.outputfile)):
                os.makedirs(os.path.dirname(self.outputfile), exist_ok=True)
        if not os.path.exists(self.temp_dir):
            os.makedirs(self.temp_dir)
        else:
            shutil.rmtree(self.temp_dir)
            os.makedirs(self.temp_dir, exist_ok=True)

    def split_cv_by_list(self):
        vccut = VideaCut(inputfile=self.inputfile, outputfile=self.outputfile)
        _name, _type = os.path.splitext(os.path.basename(self.inputfile))
        index = 0
        temp_file = os.path.join(self.temp_dir, "flist.txt")
        for split_item in self.split_list:
            stime, etime = split_item
            print(stime, etime)
            tmp_name = "{}{}".format(index, _type)
            tmp_outfile = os.path.join(self.temp_dir, tmp_name)
            vccut.set_out_file(tmp_outfile)
            vccut.cut_video_by_range_time(stime, etime)
            with open(temp_file, 'a+') as f:
                f.write("file '{}'".format(tmp_name))
                f.write('\n')

            index += 1

        vccut.set_out_file(self.outputfile)
        vccut.merge_video_by_file(temp_file)


def old_test():
    inputfile = "D:\\opt\\jq_01.mp4"
    outputfile = "D:\\opt\\output.mp4"
    split_list = [
        ['00:10:00', '00:12:00'],
        ['00:19:22', '00:20:00']
    ]

    sc = SplitVc(inputfile, outputfile, split_list)
    sc.split_cv_by_list()


def add_time(time_str):
    from datetime import datetime, timedelta

    # 初始时间转为datetime.time对象
    initial_time = datetime.strptime(time_str, "%H:%M:%S")

    # 加上29秒
    new_time = initial_time + timedelta(seconds=29)

    # 格式化输出为字符串（如果需要）
    new_time_str = new_time.strftime("%H:%M:%S")
    # print(new_time_str)
    return new_time_str

def test_sqlit():
    my_dict = {
    "jq_射雕英雄传第1集.mp4": [["00:19:50","00:22:30"],["00:25:20","00:32:00"]],
    "jq_射雕英雄传第11集.mp4": [["00:28:50","00:30:00"], ["00:40:25","00:40:56"]],
    "jq_射雕英雄传第12集.mp4": [["00:12:30","00:13:35"]],
    "jq_射雕英雄传第15集.mp4": [["00:23:10", "00:23:55"]],
    "jq_射雕英雄传第16集.mp4": [["00:02:35","00:03:30"], ["00:07:20","00:7:35"]],
    "jq_射雕英雄传第20集.mp4": [["00:08:00", "00:08:50"], ["00:20:00","00:20:55"]],
    "jq_射雕英雄传第21集.mp4": [["00:03:17","00:04:55"], ["00:11:40","00:12:40"]],
    "jq_射雕英雄传第22集.mp4": [["00:15:18","00:16:22"],["00:34:15","00:34:40"]],
    "jq_射雕英雄传第23集.mp4": [["00:02:25","00:03:01"],["00:10:15","00:11:50"]],
    "jq_射雕英雄传第25集.mp4": [["00:00:00","00:02:00"],["00:19:40","00:20:50"],["00:27:40","00:28:15"]],
    "jq_射雕英雄传第26集.mp4": [["00:06:30", "00:08:30"],["00:11:20","00:14:25"],["00:20:39","00:22:36"],
    ["00:29:10","00:31:20"]],
    "jq_射雕英雄传第27集.mp4": [["00:05:20","00:06:30"],["00:20:10","00:23:00"]],
    "jq_射雕英雄传第28集.mp4": [["00:11:10","00:13:00"]],
    "jq_射雕英雄传第29集.mp4": [["00:05:00","00:11:30"]],
    "jq_射雕英雄传第30集.mp4": [["00:07:58","00:09:00"]],
    "jq_射雕英雄传第33集.mp4": [["00:15:20","00:18:40"]],
    "jq_射雕英雄传第35集.mp4": [["00:02:45","00:10:30"]],
    "jq_射雕英雄传第38集.mp4": [["00:02:15","00:08:35"],["00:19:10","00:21:08"]],
    "jq_射雕英雄传第41集.mp4": [["00:44:10", "00:45:07"]],
    "jq_射雕英雄传第44集.mp4": [["00:20:25","00:22:55"],["00:37:10","00:38:40"]],
    "jq_射雕英雄传第47集.mp4": [["00:18:25","00:20:00"],["00:30:10","00:32:20"]],
    "jq_射雕英雄传第49集.mp4": [["00:36:15","00:37:15"]],
    "jq_射雕英雄传第50集.mp4": [["00:05:59","00:06:30"],["00:08:10","00:13:25"],["00:17:25","00:19:25"],["00:19:37","00:20:50"],["00:40:30", "00:40:55"]]

    }
    my_dict = {
        "jq_射雕英雄传第22集.mp4": [["00:15:47","00:16:22"],["00:34:15","00:34:40"]],
    }
    origin_path = "D:\\迅雷下载\\射雕剪切版"
    for inputfile, split_list in my_dict.items():
        print(inputfile, split_list)
        outputfile = "D:\\迅雷下载\\射雕胡歌精华版1\\all.mp3"
        temp_dir = "D:\\迅雷下载\\射雕胡歌精华版1"
        inputfile_real = os.path.join(origin_path, inputfile)
        vccut = VideaCut(inputfile=inputfile_real, outputfile=outputfile)
        _name, _type = os.path.splitext(os.path.basename(inputfile))
        index = 0
        temp_file = os.path.join(temp_dir, "flist.txt")
        for split_item in split_list:
            stime, etime = split_item
            stime = add_time(stime)
            etime = add_time(etime)
            print(stime, etime)
            tmp_name = "{}_{}{}".format(inputfile, index, _type)
            tmp_outfile = os.path.join(temp_dir, tmp_name)
            vccut.set_out_file(tmp_outfile)
            vccut.cut_video_by_range_time(stime, etime)
            with open(temp_file, 'a+') as f:
                f.write("file '{}'".format(tmp_name))
                f.write('\n')

            index += 1

        # vccut.set_out_file(outputfile)
        # vccut.merge_video_by_file(temp_file)


if __name__ == '__main__':
    test_sqlit()